<template>
  <!--列表-->
  <section>
    <el-form :inline="true" :model="departmentQuery" class="toolbar"
             style="text-align: left;margin-top: 20px">
      <el-form-item label="关键字">
        <el-input v-model="departmentQuery.keyword" placeholder="请输入部门名称进行查询"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch" >查询</el-button>
        <el-button type="success" @click="addDepartment">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="listDatas" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;" element-loading-text="拼命加载中">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120">
      </el-table-column>
      <el-table-column prop="intro" label="部门简介">
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180" sortable>
      </el-table-column>
      <el-table-column prop="update_time" label="更新时间" width="180" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理">
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门">
      </el-table-column>
      <el-table-column prop="path" label="路径">
      </el-table-column>
      <!--    <el-table-column prop="manager_id" label="状态" min-width="180" :formatter="formatState">-->
      <!--  </el-table-column>-->
      <el-table-column prop="state" label="状态">
        <template scope="scope">
          <span v-if="scope.row.state === 0" style="color: red">停用</span>
          <span v-if="scope.row.state === 1" style="color: green">正常</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-popconfirm
          confirmButtonText='忍心抛弃'
          cancelButtonText='再给一次机会'
          icon="el-icon-info"
          iconColor="red"
          title="你确定要离我而去？"
          @confirm="batchRemove"
      >
        <el-button type="danger" slot="reference" :disabled="this.sels.length===0">批量删除</el-button>
      </el-popconfirm>
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     :page-sizes="sizes"
                     @current-change="handleCurrentChange"
                     @size-change="handleSizeChange"
                     :current-page="currentPage"
                     :page-size="pageSize" :total="totalCount" style="float:right;">
      </el-pagination>
    </el-col>
    <!--  新增和编辑
          :visible.sync ture就打开  false就隐藏
    -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="departmentForm" :rules="departmentRules" ref="departmentForm">
        <el-form-item label="部门名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="departmentForm.name"></el-input>
        </el-form-item>
        <el-form-item label="部门介绍" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="departmentForm.intro"></el-input>
        </el-form-item>
        <!--
              managers:必须是一个数组,装的就是对象,应该是从后台查询出来
              :label:用于显示的名字
              :value:提交的数据--支持提交整个对象
              value-key="id" 绑定对象的时候必填的值
              clearable:可清空的下拉框
              filterable:可搜索
          -->
        <el-form-item label="部门经理" :label-width="formLabelWidth">
          <el-select v-model="departmentForm.manager" value-key="id" clearable filterable >
            <el-option v-for="(item,i) in managers" :label="item.username" :key="item.id" :value="item"/>
          </el-select>
        </el-form-item>
        <!--
          options:级联框数据源
          props:
            expandTrigger:打开下级的方式
            value:配置对象的里面的提交数据的key
            label:配置对象的里面的显示数据的key
            checkStrictly:可选择任意的一级
        -->
        <el-form-item label="上级部门" :label-width="formLabelWidth">
          <el-cascader
              v-model="departmentForm.parent"
              :options="deptTrees"
              :props="{ expandTrigger: 'hover',
              value: 'id',
              label: 'name',
               checkStrictly:true
               }"
              ></el-cascader>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" prop="state">
          <el-select v-model="departmentForm.state">
            <el-option label="正常" :value="1"></el-option>
            <el-option label="停用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="addLoading">确 定</el-button>
      </div>
    </el-dialog>
  </section>

</template>

<script>
import util from "../../common/js/util";
import {addUser} from "../../api/api";

export default {
  data() {
    return {
      addLoading: false,
      listDatas: [],
      listLoading: true,//开启加载效果
      sels: [],//用户多选，选中的数据
      sizes: [5, 10, 20, 50],
      currentPage: 1,
      pageSize: 5,
      totalCount: 0,
      departmentQuery: {
        keyword: '',
      },
      formLabelWidth: '120px',
      title: "新增",
      departmentForm: {
        id: null,
        name: '',
        intro: '',
        create_time: '',
        update_time: '',
        manager_id: '',
        parent_id: '',
        path: '',
        state: ''
      },
      dialogFormVisible: false,
      departmentRules: {
        name: [
          {required: true, message: '请输入部门名称', trigger: 'blur'}
        ],
        state:[
          { required: true, message: '请输选择状态', trigger: 'blur' }
        ]
      },
      managers: [],//装部门经理
      deptTrees: [],//装上级部门
    }
  },
  methods: {
    //批量删除
    batchRemove() {
      //把对象数组转成 id数组
      let deptIds = this.sels.map(function (obj,index,array){
        return obj.id;
      })
      this.$http.delete("/department/deleteList",{data:{ids:deptIds}}).then(res=>{
        let{message,success} = res.data
        if (success){
          //操作成功   给一条提示
          this.$message.success("删除成功");
        }else {
          //操作失败  给一条失败的提示
          this.$message.error("操作失败")
        }
        this.loadListData();
      })
    },
    loadListData() {
      //2、组装分页数据
      let param = {
        keyword: this.departmentQuery.keyword,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      }
      this.$http.post("/department", param).then(res => {
        let {data, success, message} = res.data;
        this.listDatas = data.dataList;
        this.totalCount = data.totals;
        console.log(this.listDatas)
        //关闭加载效果
        this.listLoading = false;
      })
    },
    loadManager() {
      this.$http.get("/employee/manager").then(res => {
        let {data, success, message} = res.data;
        this.managers = data;
      })
    },
    //性别显示转换
    formatState: function (row, column) {
      return row.state === 1 ? '启用' : row.sex === 0 ? '禁用' : '未知';
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/department/"+row.id).then(res => {
          this.listLoading = false;
          if (res.data.success){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }
          if(this.totalCount / this.pageSize)
          this.loadListData();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      // this.$refs.departmentForm.clearValidate();
      //1、获取当前行的数据
      //2、数据回显
      //3、打开弹出框
      this.title = '修改';
      this.departmentForm = row;
      console.log(this.departmentForm.parent)
      this.departmentForm.parent_id = row.parent_id;
      console.log(this.departmentForm.parent)
      this.dialogFormVisible = true;
    },
    //显示新增界面
    addDepartment: function () {
      //1、清空表单数据
      this.departmentForm = {
        id: null,
        name: '',
        intro: '',
        create_time: '',
        update_time: '',
        manager_id: '',
        parent_id: '',
        path: '',
        state: ''
      }
      this.title = '新增';
      //2、打开弹出框
      this.dialogFormVisible = true;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.currentPage = 1;
      this.loadListData();
    },
    handleCurrentChange(val) {
      //val 就是当前页的页码
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.loadListData();
    },
    onSearch() {
      this.listLoading = true;
      this.loadListData();
    },
    onSubmit() {
      this.$refs.departmentForm.validate((valid) => {
        if (valid) {
          this.addLoading = true;
          this.$confirm('确认提交吗？', '提示', {}).then(() => {

            if (this.departmentForm.parent){
              if (this.departmentForm.parent instanceof Array){
                this.departmentForm.parent_id = this.departmentForm.parent[this.departmentForm.parent.length-1];
              }else {
                this.departmentForm.parent_id = this.departmentForm.parent;
              }
            }
            //无论如何都要把this.departmentForm.parent置为空
            this.departmentForm.parent = null;

            this.$http.put('/department', this.departmentForm).then(res => {
              this.addLoading = false;
              if (res.data.success) {
                this.$message.success("添加操作成功！");
              }else {
                this.$message.error("添加操作失败！");
              }
              this.dialogFormVisible=false;
              this.loadListData();
            });
          }).catch(() => {
            this.addLoading = false;
            this.$message.info("取消操作");
          })
        }
      });
    },
    loadDeptTree() {
      this.$http.get('/department/deptTree').then(res=>{
        this.deptTrees = res.data.data;
      })
    },
  },
  mounted() {
    //加载完毕以后调用获取列表数据的方法
    this.loadListData();
    this.loadManager();
    this.loadDeptTree();

  }
}
</script>

<style scoped>

</style>